#ifndef TCP_TCPSERVER_H
#define TCP_TCPSERVER_H

#include "tcp/Acceptor.h"
#include "TcpConnection.h"
#include "reactor/EventLoopThreadPool.h"

#include <map>
#include <memory>

class TcpServer {
public:
    enum Option {
        kNoReusePort,
        kReusePort,
    };

    TcpServer(EventLoop *loop,
              const InetAddress &listenAddr,
              std::string name = "myTcpServer",
              Option option = kNoReusePort);

    ~TcpServer();

    void start();

    void
    setConnectionCallback(const ConnectionCallback &connectionCallback) { connectionCallback_ = connectionCallback; }

    void setMessageCallback(const MessageCallback &messageCallback) { messageCallback_ = messageCallback; }

    void setCloseCallback(const CloseCallback &closeCallback) { closeCallback_ = closeCallback; }

    void setWriteCompleteCallback(
            const WriteCompleteCallback &writeCompleteCallback) { writeCompleteCallback_ = writeCompleteCallback; }

    void setThreadNum(int threadNums);

    EventLoop *getLoop() const { return loop_; }

    const string &name() const { return name_; }

private:
    typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;

    void newConnection(int sockfd, const InetAddress &peerAddr);

    void removeConnection(const TcpConnectionPtr &conn);

    void removeConnectionInLoop(const TcpConnectionPtr &conn);

    EventLoop *loop_;
    // TcpServer 对应的事件循环, 这里的事件循环是对应用于监听listen的循环
    const std::string name_;
    std::unique_ptr<Acceptor> acceptor_;
    // 适配器, 用于适配接收方式用
    std::unique_ptr<EventLoopThreadPool> threadPool_;
    // 事件循环池, 当新连接到达的时候就会从事件池中获取事件循环来工作

    ConnectionCallback connectionCallback_;
    MessageCallback messageCallback_;
    CloseCallback closeCallback_;
    WriteCompleteCallback writeCompleteCallback_;
    // 上面这几个都是连接对应的调用函数, 负责填充进连接用的

    ConnectionMap connections_;
    // 持有当前存活的TcpConnection 的shar_ptr指针,

    bool started_;
    int nextConnId_;
};

#endif //TCP_TCPSERVER_H
